﻿using Freshbox2._0.BLL;
using Freshbox2._0.MODEL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Freshbox2._0.UI.Controllers
{
    public class AvgMoneyRateChartController : BaseController<usersorder>
    {
        //
        // GET: /AvgMoneyRateChart/

        public override BLL.BaseBll<usersorder> bll
        {
            get
            {
                return new UsersOrderBll();
            }

        }

        public class RateChartModel
        {
            //public string shopName;  
            public decimal AllRate; //  总利润  客单价  PerPrice
            public decimal AvgRate;  // 平均利润 客单量  CustomerSum 
            public string Date; 


        }

        public class SaleDetailModel
        {
            public int saleNum  { get; set; }  // 封装 之后下面才能 searchBySQL 出来结果 不然为null
            public decimal waresBid  { get; set; }
            public decimal waresPrice  { get; set; }
            public decimal money { get; set; }
        }


        StoreBll storeBll = new StoreBll();

        OrderDetailsBll orderDetailBll = new OrderDetailsBll();

        WaresBll waresBll = new WaresBll();

        public decimal? SaleMoney;

        public decimal? BuyMoney;


        /// <summary>
        /// 总利润   平均利润  走势
        /// </summary>
        /// <param name="date1"></param>
        /// <param name="date2"></param>
        /// <returns></returns>

        public ActionResult PerCustomerPrice(string date1, string date2, string storeid)
        {
            int shopNum = storeBll.Search(x=>x.storeStatus==1).ToList().Count;
            var dataList = new List<RateChartModel>();
            //   默认查询本天 之前的 一周的记录  总的店铺的
            if (string.IsNullOrEmpty(date1) && string.IsNullOrEmpty(date2) && string.IsNullOrEmpty(storeid))
            {
                //先算6 天的   
                for (var i = 0; i <= 6; i++)
                {
                    var countData = i;
                    //查出 今日总的销售
                    var query = orderDetailBll.Search();

                    var list2 = orderDetailBll.Search().Where(x =>  x.usersorder.orderStatus == 1).
                        GroupBy(x => x.waresCode).Select(x => new
                    {
                        waresQuantity=x.Sum(y => y.waresQuantity) ,
                        x.FirstOrDefault().wares.waresBid,
                    
                        x.FirstOrDefault().wares.waresPrice,

                    });
                    var  sql2 = list2.ToString();
                    var list = query.Where(x => x.orderTime.Date == DateTime.Now.Date.AddDays(-countData) && x.usersorder.orderStatus == 1).GroupBy(x => x.waresCode).Select(x => new
                       {
                           allBuyPrice= x.Sum(y => y.waresQuantity)*x.FirstOrDefault().wares.waresBid,
                           allSalePrice = x.Sum(y => y.waresQuantity) * x.FirstOrDefault().wares.waresPrice,
  
                       }).ToList();
                    SaleMoney = list.Sum(y => y.allSalePrice);
                    BuyMoney = list.Sum(y => y.allBuyPrice);
 
                    RateChartModel rate = new RateChartModel();
                    rate.Date = DateTime.Now.Date.AddDays(-countData).ToString("yy/MM/dd");
                    rate.AllRate =Convert.ToDecimal(  SaleMoney - BuyMoney);
                   // rate.AvgRate = Convert.ToDecimal((SaleMoney - BuyMoney) / shopNum); 
                    dataList.Add(rate);
                    SaleMoney = 0;
                    BuyMoney = 0;
                }
                var dataArray = dataList.ToArray();
                return Json(dataList, JsonRequestBehavior.AllowGet);
            }
            //按店铺查询 
            if (string.IsNullOrEmpty(date1) && string.IsNullOrEmpty(date2) && storeid != "" && storeid != null)
            {
                int storeID = Convert.ToInt32(storeid);
                //先算6 天的   
                for (var i = 0; i <= 6; i++)
                {

                    var countData = i;
                    var query = orderDetailBll.Search().ToList();
                    var list = query.Where(x => x.orderTime.Date == DateTime.Now.Date.AddDays(-countData) && x.usersorder.orderStatus == 1 && x.storeid == storeID).GroupBy(x => x.waresCode).Select(x => new
                    {
                        allBuyPrice = x.Sum(y => y.waresQuantity) * x.FirstOrDefault().wares.waresBid,
                        allSalePrice = x.Sum(y => y.waresQuantity) * x.FirstOrDefault().wares.waresPrice,
                    }).ToList();
                    SaleMoney = list.Sum(y => y.allSalePrice);
                    BuyMoney = list.Sum(y => y.allBuyPrice);
                    RateChartModel rate = new RateChartModel();
                    rate.Date = DateTime.Now.Date.AddDays(-countData).ToString("yy/MM/dd");
                    rate.AllRate = Convert.ToDecimal(SaleMoney - BuyMoney);
                    //rate.AvgRate = Convert.ToDecimal((SaleMoney - BuyMoney) / shopNum);
                    dataList.Add(rate);
                    SaleMoney = 0;
                    BuyMoney = 0;
                }
                var dataArray = dataList.ToArray();
                return Json(dataList, JsonRequestBehavior.AllowGet);
            }
            //按日期查询 总的
            if (date1 != null && date1 != "" && date2 != null && date2 != "" && string.IsNullOrEmpty(storeid))
            {
                DateTime datetime1 = DateTime.Parse(date1);
                DateTime datetime2 = DateTime.Parse(date2).AddDays(1);
                TimeSpan sp = datetime2.Subtract(datetime1);  //这里验证通过  不在一个月的日期也可以  
                 
                //相差天数  
                int dayMin = sp.Days;
                for (var i = 0; i < dayMin; i++)
                {
                    var countData = i;

                    DateTime date11 = datetime1.Date.AddDays(+countData);

                    var query = orderDetailBll.Search().ToList();
                    var list = query.Where(x => x.orderTime.Date == date11.Date && x.usersorder.orderStatus == 1).GroupBy(x => x.waresCode).Select(x => new
                    {
                        allBuyPrice = x.Sum(y => y.waresQuantity) * x.FirstOrDefault().wares.waresBid,
                        allSalePrice = x.Sum(y => y.waresQuantity) * x.FirstOrDefault().wares.waresPrice,
                    }).ToList();
                    SaleMoney = list.Sum(y => y.allSalePrice);
                    BuyMoney = list.Sum(y => y.allBuyPrice);
                    RateChartModel rate = new RateChartModel();
                    rate.Date = DateTime.Now.Date.AddDays(-countData).ToString("yy/MM/dd");
                    rate.AllRate =Convert.ToDecimal(  SaleMoney - BuyMoney);
                    rate.AvgRate = Convert.ToDecimal((SaleMoney - BuyMoney) / shopNum);
                    dataList.Add(rate);
                    SaleMoney = 0;
                    BuyMoney = 0;
                }
                var dataArray = dataList.ToArray();
                return Json(dataList, JsonRequestBehavior.AllowGet);
            }
            //按日期查询 跟店铺查询
            if (date1 != null && date1 != "" && date2 != null && date2 != "" && storeid != "" && storeid != null)
            {
                int storeID = Convert.ToInt32(storeid);
                DateTime datetime1 = DateTime.Parse(date1);
                DateTime datetime2 = DateTime.Parse(date2).AddDays(1);
                TimeSpan sp = datetime2.Subtract(datetime1);  //这里验证通过  不在一个月的日期也可以  

                //相差天数
                int dayMin = sp.Days;
                for (var i = 0; i < dayMin; i++)
                {
                    var countData = i;
                    DateTime date11 = datetime1.Date.AddDays(+countData);
                    var query = orderDetailBll.Search().ToList();
                    var list = query.Where(x => x.orderTime.Date == date11.Date && x.usersorder.orderStatus == 1 && x.storeid == storeID).GroupBy(x => x.waresCode).Select(x => new
                    {
                        allBuyPrice = x.Sum(y => y.waresQuantity) * x.FirstOrDefault().wares.waresBid,
                        allSalePrice = x.Sum(y => y.waresQuantity) * x.FirstOrDefault().wares.waresPrice,
                    }).ToList();
                    SaleMoney = list.Sum(y => y.allSalePrice);
                    BuyMoney = list.Sum(y => y.allBuyPrice);
                    RateChartModel rate = new RateChartModel();
                    rate.Date = DateTime.Now.Date.AddDays(-countData).ToString("yy/MM/dd");
                    rate.AllRate =Convert.ToDecimal(  SaleMoney - BuyMoney);
                    //rate.AvgRate =Convert.ToDecimal(  (SaleMoney - BuyMoney) /shopNum);
                    dataList.Add(rate);
                    SaleMoney = 0;
                    BuyMoney = 0;
                }
                var dataArray = dataList.ToArray();
                return Json(dataList, JsonRequestBehavior.AllowGet);      
            }
            return Json(dataList, JsonRequestBehavior.AllowGet);
        }


        //测试优化 通过sql语句 总利润   平均利润  走势
        public ActionResult RateChart(string date1, string date2, string storeid)
        {
            var list = new List<RateChartModel>();
            StringBuilder sql = new StringBuilder();
            //默认查询本天 之前的 一周的记录  总的店铺的 
            if (string.IsNullOrEmpty(date1) && string.IsNullOrEmpty(date2) && string.IsNullOrEmpty(storeid))
            {
                //先算6 天的   
                for (var i = 0; i <= 6; i++)
                {
                    var countData = i;
                    sql.Append("select sum(b) as money from (select sum(waresQuantity)*(orderdetails.waresPrice-wares.waresBid) as b from orderdetails  force index(idx_orderdetails_orderTime)  inner join usersorder on orderdetails.orderCode=usersorder.orderCode INNER JOIN wares on wares.waresCode=orderdetails.waresCode where usersorder.orderStatus=1  and TO_DAYS(NOW())-TO_DAYS(orderdetails.orderTime) = " + countData + "  GROUP BY orderdetails.waresCode )  as a  ");
                    var a = bll.SearchBySQL<SaleDetailModel>(sql.ToString()).ToList();
                    RateChartModel chartModel = new RateChartModel();
                    chartModel.Date = DateTime.Now.Date.AddDays(-countData).ToString("yy/MM/dd");
                    chartModel.AllRate = a.FirstOrDefault().money;     //今日份利润
                    list.Add(chartModel);
                    sql.Clear();//清空sql语句
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(date1) && !string.IsNullOrEmpty(date2))
                {
                    int shopid =0;
                    DateTime datetime1 = DateTime.Parse(date1);
                    DateTime datetime2 = DateTime.Parse(date2);
                    TimeSpan sp = datetime2.Subtract(datetime1);  //这里验证通过  不在一个月的日期也可以  
                    if (!string.IsNullOrEmpty(storeid))
                    {
                          shopid = Convert.ToInt32(storeid);
                    }
                    //相差天数  
                    int dayMin = sp.Days+1;
                    for (var i = 0; i < dayMin; i++)
                    {
                        var countData = i;
                        if (!string.IsNullOrEmpty(storeid))
                        {
                            sql.Append("select sum(b)  as money  from (select sum(waresQuantity)*(orderdetails.waresPrice-wares.waresBid) as b  from orderdetails   force index(idx_orderdetails_orderTime)  inner join usersorder on orderdetails.orderCode=usersorder.orderCode INNER JOIN wares on wares.waresCode=orderdetails.waresCode where usersorder.orderStatus=1 AND orderdetails.storeid=" + shopid + "  and TO_DAYS('" + datetime2 + "')-TO_DAYS(orderdetails.orderTime) = " + countData + "  GROUP BY orderdetails.waresCode )  as a  ");

                        }
                        else
                        {
                            sql.Append("select sum(b)  as money  from (select sum(waresQuantity)*(orderdetails.waresPrice-wares.waresBid) as b   from orderdetails force index(idx_orderdetails_orderTime)  inner join usersorder on orderdetails.orderCode=usersorder.orderCode INNER JOIN wares on wares.waresCode=orderdetails.waresCode where usersorder.orderStatus=1  and TO_DAYS('" + datetime2 + "')-TO_DAYS(orderdetails.orderTime) = " + countData + "  GROUP BY orderdetails.waresCode )  as a ");

                        }
                        var a = bll.SearchBySQL<SaleDetailModel>(sql.ToString()).ToList();
                        RateChartModel chartModel = new RateChartModel();
                        chartModel.Date = datetime2.Date.AddDays(-countData).ToString("yy/MM/dd");
                        chartModel.AllRate = a.FirstOrDefault().money;//今日份利润
                        list.Add(chartModel);                        
                        sql.Clear();//清空sql语句
                    }
                    list = list.OrderBy(x => x.Date).ToList();//正序排列
                }

            }
            return Json(list, JsonRequestBehavior.AllowGet);
        }
    }

}

